//
//  AudioMetricsView.swift
//  SpeechAnalyzerDemo
//
//  使用 UIKit 组件展示声道功率数据。
//

import UIKit
import AVFAudio

final class AudioMetricsView: UIView {

    private let elapsedLabel = UILabel()
    private let channelsStack = UIStackView()

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupLayout()
        configureUI()
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func update(with powerLevels: [PowerLevel], elapsed: TimeInterval) {
        elapsedLabel.text = "Elapsed time: \(elapsed.secondString)"

        channelsStack.arrangedSubviews.forEach { subview in
            channelsStack.removeArrangedSubview(subview)
            subview.removeFromSuperview()
        }

        for level in powerLevels {
            channelsStack.addArrangedSubview(makeChannelView(for: level))
        }
    }
}

// MARK: - 布局与渲染
private extension AudioMetricsView {
    func setupLayout() {
        let container = UIStackView(arrangedSubviews: [elapsedLabel, channelsStack])
        container.axis = .vertical
        container.spacing = 16
        container.translatesAutoresizingMaskIntoConstraints = false

        channelsStack.axis = .vertical
        channelsStack.spacing = 16

        addSubview(container)
        NSLayoutConstraint.activate([
            container.leadingAnchor.constraint(equalTo: layoutMarginsGuide.leadingAnchor),
            container.trailingAnchor.constraint(equalTo: layoutMarginsGuide.trailingAnchor),
            container.topAnchor.constraint(equalTo: layoutMarginsGuide.topAnchor),
            container.bottomAnchor.constraint(equalTo: layoutMarginsGuide.bottomAnchor)
        ])
    }

    func configureUI() {
        elapsedLabel.font = .preferredFont(forTextStyle: .subheadline)
        elapsedLabel.textColor = .label

        backgroundColor = .secondarySystemBackground
        layer.cornerRadius = 8
        layoutMargins = UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12)
    }

    func makeChannelView(for level: PowerLevel) -> UIView {
        let container = UIStackView()
        container.axis = .vertical
        container.spacing = 8

        let titleLabel = UILabel()
        titleLabel.text = "Channel (Bus): \(level.channel)"
        titleLabel.font = .preferredFont(forTextStyle: .subheadline)
        titleLabel.textColor = .label

        let averageProgress = UIProgressView(progressViewStyle: .default)
        averageProgress.progress = normalized(level.average.linearPower)

        let averageLabel = UILabel()
        averageLabel.text = "Average Power: \(level.average.powerString)"
        averageLabel.font = .preferredFont(forTextStyle: .footnote)
        averageLabel.textColor = .secondaryLabel

        let peakProgress = UIProgressView(progressViewStyle: .default)
        peakProgress.progressTintColor = .systemOrange
        peakProgress.progress = normalized(level.peak.linearPower)

        let peakLabel = UILabel()
        peakLabel.text = "Peak Power: \(level.peak.powerString)"
        peakLabel.font = .preferredFont(forTextStyle: .footnote)
        peakLabel.textColor = .secondaryLabel

        container.addArrangedSubview(titleLabel)

        let averageStack = UIStackView(arrangedSubviews: [averageLabel, averageProgress])
        averageStack.axis = .vertical
        averageStack.spacing = 4

        let peakStack = UIStackView(arrangedSubviews: [peakLabel, peakProgress])
        peakStack.axis = .vertical
        peakStack.spacing = 4

        container.addArrangedSubview(averageStack)
        container.addArrangedSubview(peakStack)

        return container
    }

    func normalized(_ value: Float) -> Float {
        let bounded = max(0, min(1, value))
        return bounded
    }
}
